<template>
  <div>
    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='allcustomersPLxGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
        <template #form>
          <div>
            <!--搜索-->
            <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
              <el-form-item label="客户名称：">
                <el-select
                  clearable
                  v-model="listQuery.customerId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="querySearch">
                  <el-option
                    v-for="item in querySearchList"
                    :key="item.customerId"
                    :label="item.customerName"
                    :value="item.customerId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最新跟进时间：">
                <el-date-picker
                  v-model="listQuery.cglTrackingTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="未跟进天数：">
                <el-select v-model="listQuery.cglTrackingTimeType" clearable>
                  <el-option value="sevenDaysMore" label="超7天"></el-option>
                  <el-option value="fifteenDaysMore" label="超15天"></el-option>
                  <el-option value="thirtyDaysMore" label="超30天"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最新成交时间：">
                <el-date-picker
                  v-model="listQuery.cglOrderTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="未成交天数：">
                <el-select v-model="listQuery.cglOrderTimeType" clearable>
                  <el-option value="sevenDaysMore" label="超7天"></el-option>
                  <el-option value="fifteenDaysMore" label="超15天"></el-option>
                  <el-option value="thirtyDays" label="超30天"></el-option>
                  <el-option value="thirtyDaysMore" label="超60天"></el-option>
                  <el-option value="ninetyDaysMore" label="超90天"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="统一信用码：">
                <el-input v-model="listQuery.businessCode" class="input-width" style="width:195px"></el-input>
              </el-form-item>
              <el-form-item label="采购等级：">
                <el-select v-model="listQuery.customerLabel" multiple class="input-width" style="width:195px" placeholder="请选择" clearable>
                  <el-option value="A类" label="A类" key="A类"></el-option>
                  <el-option value="B类" label="B类" key="B类"></el-option>
                  <el-option value="C类" label="C类" key="C类"></el-option>
                  <el-option value="D类" label="D类" key="D类"></el-option>
                  <el-option value="E类" label="E类" key="E类"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户分类：">
                <el-select v-model.number="listQuery.customerType" class="input-width" style="width:195px" placeholder="请选择" clearable>
                  <el-option :value="item.cddId" :label="item.cddValue" :key="item.cddId" v-for="item in customerTypeList"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户行业：">
                <el-cascader
                  v-model="listQuery.customerIndustry"
                  :options="options2"
                  :props="{ value:'typeId',label:'typeName',emitPath:false}"
                  clearable></el-cascader>
              </el-form-item>
              <el-form-item label="客户来源：" >
                <el-select v-model.number="listQuery.customerSource" class="input-width" style="width:195px" placeholder="请选择" clearable>
                  <el-option :value="item.cddId" :label="item.cddValue" :key="item.cddId" v-for="item in customerSourceList"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户等级：">
                <el-select v-model.number="listQuery.customerGrade" class="input-width" style="width:195px" placeholder="请选择" clearable>
                  <el-option value="A1" label="A1" key="A1"></el-option>
                  <el-option value="A2" label="A2" key="A2"></el-option>
                  <el-option value="A3" label="A3" key="A3"></el-option>
                  <el-option value="A4" label="A4" key="A4"></el-option>
                  <el-option value="B" label="B" key="B"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所在地区：">
                <el-cascader
                  v-model="listQuery.areaId"
                  :options="options"
                  :props="{ checkStrictly: true ,value:'areaId',label:'areaName',emitPath:false,children:'areaChildList'}"
                  clearable></el-cascader>
              </el-form-item>
              <el-form-item label="潜在等级：">
                <el-select v-model="listQuery.customerPotential" class="input-width" style="width:195px" placeholder="请选择" multiple>
                  <el-option
                    v-if="item.customerPotentialValue.indexOf('Z') == -1"
                    v-for="item in customerPotentialList"
                    :key="item.customerPotentialId"
                    :label="item.customerPotentialValue"
                    :value="item.customerPotentialId">
                  </el-option>
                  <el-option
                    :key="0"
                    label="无潜在等级"
                    :value="0">
                  </el-option>
                </el-select>
              </el-form-item>
<!--              <el-form-item label="只显示主客户：">-->
<!--                <el-select v-model="listQuery.isMainCustomer" class="input-width" style="width:195px" placeholder="请选择">-->
<!--                  <el-option-->
<!--                    key="1"-->
<!--                    label="是"-->
<!--                    value="1">-->
<!--                  </el-option>-->
<!--                  <el-option-->
<!--                    :key="0"-->
<!--                    label="否"-->
<!--                    value="0">-->
<!--                  </el-option>-->
<!--                </el-select>-->
<!--              </el-form-item>-->
              <el-form-item label="是否为成交客户：">
                <el-select v-model="listQuery.isHasOrder" class="input-width" style="width:195px" placeholder="请选择">
                  <el-option
                    key="1"
                    label="是"
                    value="1">
                  </el-option>
                  <el-option
                    :key="0"
                    label="否"
                    value="0">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序：">
                <el-select v-model="listQuery.sort"  placeholder="请选择" clearable>
                  <el-option key="1" label="最新跟进时间倒序" value="1"></el-option>
                  <el-option key="2" label="最新跟进时间升序" value="2"></el-option>
                  <el-option key="3" label="最新成交时间倒序" value="3"></el-option>
                  <el-option key="4" label="最新成交时间升序" value="4"></el-option>
                  <el-option key="5" label="成交量升序" value="5"></el-option>
                  <el-option key="6" label="成交量倒序" value="6"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="负责人：">
                <el-select v-model="listQuery.chargeId"  placeholder="请选择" clearable filterable multiple >
                  <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button
                  @click="handleSearchList()"
                  type="primary">
                  查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>

        </template>
        <template #toolbar_buttons>
           <export-pop ref="exportPop" @click.native="downloadExcel" v-if="listQuery.tab == 'all' && !listQuery.sub && exportAllCustomer"></export-pop>
           <el-button type="primary" size="small" @click="showAdd" v-if="listQuery.tab == 'all' && !listQuery.sub">新增产品线</el-button>
          <span style="padding-left:20px">合计客户数：{{count}}个</span>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <div @click="toDetail(row)" type="primary"  style="font-size:12px;vertical-align: middle;cursor:pointer;text-align: center;color:#409EFF">
            <div>{{row.customerName}}</div>
            <div>{{row.kingNumber}}</div>
          </div>
        </template>
        <template #num2_default="{ row, rowIndex }">
          <span v-for="item in row.relationCustomers" style="padding-left:10px">{{item.customerName}}</span>
        </template>
      </vxe-grid>
      <el-dialog :close-on-click-modal="false" title="新增客户产品线" :visible.sync="dialogVisible" width="500px">
        <el-form  :model="form" size="mini" label-width="100px" ref="form" :rules="rules">
          <el-form-item label="客户名称：">
              {{form.customerNames}}
          </el-form-item>
          <el-form-item label="产品线：" prop="goodsLineId">
            <el-select v-model="form.goodsLineId" filterable clearable>
              <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人：" prop="chargeId">
            <el-select v-model="form.chargeId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
      </el-dialog>
    </div>
    <gjList ref="gjList"></gjList>
    <lxrList ref="lxrList"></lxrList>
  </div>
</template>
<script>
import {getCustomerOption,getOrderUsersList,getAddressList,customerPotential,getCustomerSetting,getUserOption} from '@/api/partner'
import {goodsLineMyCustomer,productCustomersTreeTypeList,customerAllCustomers,customerNewBatchGoodLine} from '@/api/company'
import {formatDate} from '@/utils/date';
import exportPop from './exportPop.vue'
import gjList from './gjList';
import lxrList from './lxrList';

import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  tab:'all',
  "customerId" : "", //客户ID
  "businessCode" : "", //统一信用码
  "customerLabel" : "", //采购评级
  "customerType" : "", //客户分类
  "customerIndustry" : "", //客户行业
  "customerSource" : "", //客户来源
  "customerGrade" : "", //客户等级
  "areaId" : "", //所在地区ID
  "customerPotential" : "", //潜在等级
  "isMainCustomer" : 1, //筛选主客户
  "isHasOrder" : "", //是否是成交客户
  cglTrackingTime:[],//最新跟进时间
  cglOrderTime:[],//最新成交时间
  "trackingTimeType" : "", //跟进时间时间类型(今天-today,7天内-sevenDays,超7天-sevenDaysMore,超15天-fifteenDaysMore，超30天-thirtyDaysMore)
  "orderTimeType" : "",  //最新成交时间类型(超7天-sevenDaysMore，超15天-fifteenDaysMore，超30天-thirtyDays,超60天-thirtyDaysMore，超90天-ninetyDaysMore)
  "sort" : "", //排序(最近跟进时间-trackingTimeDesc,最近成交时间-cglOrderTime,最新跟进成交时间-trackingOrderTime)
  "pageNum" : 1,
  "pageSize" : 10,
  docking:false,
  chargeId:[]
};

const defaultForm = {
  customerIds:'',
  customerNames:'',
  goodsLineId:'',
  chargeId:''//
};

export default {
  name: "index",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      gridOptions:{
        border: true,
        id: 'allcustomersPL',
        align:'center',
        rowConfig: {
          keyField: 'customerId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [

          { type: 'checkbox',
            title: '',
            fixed:'left',
            width: 50,
          },
          {
            field: '',
            title: '客户名称',
            width: 150,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'businessCode',
            title: '社会统一信用码',
            width: 150,
          },
          {
            field: 'goodsLineNames',
            title: '产品线',
            width: 150,
          },
          {
            field: 'chargeName',
            title: '负责人',
            width: 100,
          },
          {
            field: 'relationCustomers',
            title: '关联子客户',
            width: 150,
          },
          {
            field: 'typeList',
            title: '类别',
            width: 100,
            slots: {
              // 使用 JSX 渲染
              default: ({ row }) => {
                if(row.typeList == 'isBlackList'){
                  return '黑名单'
                }else if(row.typeList == 'isDelete'){
                  return  '回收站'
                }else if(row.typeList == 'noCharge'){
                  return  '公海'
                }else if(row.typeList == 'normal'){
                  return  '正常'
                }else if(row.typeList == 'isBlackListApply'){
                  return  '黑名单待审'
                }else if(row.typeList == 'isDeleteApply'){
                  return  '回收站待审'
                }else if(row.typeList == 'outNoCharge'){
                  return  '领取客户待审'
                }else if(row.typeList == 'moveCharge'){
                  return  '转移客户待审核'
                }

              }
            },
          },
          {
            field: 'areaNames',
            title: '所在地区',
            width: 150,

          },
          {
            field: 'customerPotential',
            title: '潜在等级',
            width: 100,
          },
          {
            field: 'customerLabel',
            title: '采购评级',
            width: 100,
          },
          {
            field: 'trackingTime',
            title: '最近跟进时间',
            width: 150,
          },
          {
            field: 'trackingContent',
            title: '最近跟进内容',
            showOverflow:true,
            width: 150,
          },
          {
            field: 'orderNum',
            title: '成交量',
            showOverflow:true,
            width: 100,
          },
          {
            field: 'abutmentNum',
            title: '转售量',
            width: 100,
          },
          {
            field: 'orderTime',
            title: '最近成交时间',
            showOverflow:true,
            width: 150,
          },
          {
            field: 'customerType',
            title: '客户分类',
            width: 100,
          },
          {
            field: 'customerIndustry',
            title: '客户行业',
            width: 150,
          },
          {
            field: 'customerQuantity',
            title: '客户性质 ',
            width: 150,
          },
          {
            field: 'customerSource',
            title: '客户来源 ',
            width: 150,
          }, {
            field: 'createdTime',
            title: '创建日期 ',
            width: 100,
          },{
            field: 'createUserName',
            title: '创建人 ',
            width: 100,
          },
          {
            field: '',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用 JSX 渲染
              default: ({ row }) => {
                if(this.listQuery.tab == 'all' && this.listQuery.isMainCustomer == 1){
                  return [
                    <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.showPop2(row) }>跟进记录</el-button>,
                    // <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.showPop3(row) }>联系人</el-button>,
                  ]
                }else{
                  return  ''
                }

              }
            },
          },
        ],
        data:[],
      },
      querySearchList:[],
      options:[],
      customerSourceList:[],
      customerPotentialList:[],
      customerTypeList:[],
      options2:[],

      dialogVisible:false,
      btnLoading:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      userOptionList:[],
      rules:{
        goodsLineId: [{required: true, message: '此项必填', trigger: 'change'},],
        chargeId:[{required: true, message: '此项必填', trigger: 'change'},],
      },

      goodsLineList:[],

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    exportAllCustomer(){
      if(this.roles.indexOf("exportAllCustomer") != -1){
        return true
      }else{
        return false
      }
    },
  },
  components : {
    exportPop,
    gjList,
    lxrList,
  },
  created() {

  },
  filters: {

  },
  methods:{


    //显示跟进记录
    showPop2(item){
      this.$refs.gjList.showPop(item,'customer')
    },
    //显示联系人
    showPop3(item){
      this.$refs.lxrList.showPop(item,'customer')
    },
    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },
    showAdd(){
      let list = this.$refs.allcustomersPLxGrid.getCheckboxReserveRecords();
      let list2 = this.$refs.allcustomersPLxGrid.getCheckboxRecords();
      let records = JSON.parse(JSON.stringify(list.concat(list2)));
      if(records.length == 0){
        this.$message({
          type: 'info',
          message: '请先选择记录！'
        });
        return false
      }
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      let customerIds = [];
      let customerNames = []
      records.forEach((el)=>{
        customerIds.push(el.customerId)
        customerNames.push(el.customerName)
      })
      this.form.customerIds = customerIds.join(",")
      this.form.customerNames = customerNames.join(",")
    },

    //添加客户产品线
    handleConfirm(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          customerNewBatchGoodLine(data).then(()=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getList()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },

    downloadExcel(){
      this.$refs.exportPop.downloadExcel('exportCustomer',this.listQuery)
    },

    toDetail(item){
      let routeData = this.$router.resolve({name:'customerGoodsLineInfo',query:{id:item.customerId}});
      window.open(routeData.href);
    },
    toAdd(){
      this.$router.push({name:'addCustomerPL'})
    },
    init(key){
      this.listQuery.tab = key;
      this.listQuery.docking = this.$parent.type === 'docking'
      this.listQuery.isMainCustomer = this.$parent.type === 'sub' ? 0 : 1
      this.handleSearchList();
      this.getUserOptionList()
      this.getCustomerSettingList();
      this.getCustomerPotential();
      this.getCustomersTreeTypeList();
      this.getAddressListData()

    },
    //获取客户行业列表
    getCustomersTreeTypeList(){
      this.dataLoading = true;
      productCustomersTreeTypeList({code:2}).then((res)=>{
        this.options2 = this.forTree(res);
      })
    },

    //去除不要的children
    forTree(list){
      let newList = list;
      if(newList.length){
        for (let i = 0; i<newList.length; i++){
          if(newList[i].children && newList[i].children.length > 0){
            this.forTree(newList[i].children)
          }else{
            delete newList[i].children;
          }
        }
        return newList
      }
    },

    //获取潜在等级
    getCustomerPotential(){
      customerPotential().then((res)=>{
        this.customerPotentialList = res;
      })
    },

    //获取客户配置
    getCustomerSettingList(){
      getCustomerSetting().then((res)=>{
        res.forEach((el)=>{
          if(el.cdtCode == 'customer_source'){
            this.customerSourceList = el.data;
          }else if(el.cdtCode == 'customer_type'){
            this.customerTypeList = el.data;
          }else if(el.cdtCode == 'goods_line'){
            this.goodsLineList = el.data
          }
        });
      })
    },

    //获取省市区列表
    getAddressListData(){
      getAddressList().then((res)=>{
        this.options = res;
      })
    },


    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= '') {
        getCustomerOption({keywords: queryString}).then((res) => {
          this.querySearchList = res;
        })
      }
    },



    //选择员工名称
    handleSelectUserName(key,item){
      this.listQuery[key] = item.userId;
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      customerAllCustomers(this.listQuery).then(response => {
        this.gridOptions.data = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },
  },
}
</script>

<style  lang="scss">

</style>
